// WhiteboardMonitor

package com.ibm.tspaces.examples.whiteboard;

import  java.util.*;
import  java.text.*;
import  java.io.*;
import  com.ibm.tspaces.*;

/*
**  Licensed Materials - Property of IBM
**
**  (C) COPYRIGHT IBM Corp. 1996, 1997  All rights reserved
**
**  US Government Users Restricted Rights - Use, duplication or
**  disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
**
**/
/**
** This class will create the WhiteBoard TupleSpace 
** and then just check every so often that the server
** is still alive.  
**
** @see Whiteboard
** @version $Revision: 2.1 $ $Date: 1999/11/05 22:22:40 $
** @author John Thomas
*/

public class WhiteboardMonitor {
  
  private static final int DELAY_TIME = 30*60*1000;
  
  private static final String SYSADMIN = "tspaces@almaden.ibm.com";
  private static final String SERVICE_HOST = "tspaces.almaden.ibm.com"; 
  
  public static void main( String argv[] ) {
  	
  	String	host	=	"localhost";
	int 	port	=   TupleSpace.DEFAULTPORT;
	String  user	=   "sysadmin";
	String  pass	=   "";
	boolean check	=   false;
	boolean sentmsg =   false;
	
    if (argv.length == 0) {
    	System.out.println("Syntax: java classname host port password CHECK");
    	System.exit(1);
    }
    
    try {
      	if (argv.length > 0) 
      		host = argv[0];
      	if (argv.length > 1)       	
      		port = new Integer(argv[1]).intValue();
      	if (argv.length > 2) 
      		pass = argv[2];
      	if (argv.length >3)   // If any 4th argument then do check loop 
      		check = true;	
    } catch(Exception e) {
    	System.out.println(e);
        e.printStackTrace();
        System.exit(1);

    }
  			
    boolean running = false;
    int counter = 0;
    String errmsg = ""; 
    TupleSpace ts = null;
    print("Started",true);
    TupleSpace.connectionTries(1);
   	while (true) {
   		
    	try { 
    	    if (counter++ > 0)  // don't delay the 1st time
    			Thread.sleep(DELAY_TIME);   
    		if (! running)  {
    			print("Allocate Whiteboard@"+host+":"+port); 
    			// Allocate the Whiteboard Tuplespace
		      	ts = new TupleSpace("Whiteboard",
	      				host,port,
	      				null,null,
	      				user,pass);
	      		
	      	}
    	    /******  This will not work because status is broken
    	             and requires admin access by anonymous       
	      	Tuple active = TupleSpace.status(host,port);
	      
	      
	       	// 
	       	System.out.println(active);
	       	if ( active == null || active.getField(0).value().equals("NotRunning")) {
	           System.out.println("Server not running on " +     host+":"+port );      		
	      	} 
	      	******/
	      
		      	
      		// Read a tuple from the TupleSpace
      		// We don't care if it actually reads anything
            // As long as it does not throw an exception 
		    Tuple t1 = new Tuple("XXXX");	
	  	    Tuple result = ts.read(t1);     // we don't really expect an answer
	  	    if ( !running) {      // Get here only if no exception on ts.read
	  	    	print("Server is now started");
				running = true;
				if (sentmsg) {  // send OK msg if already sent down msg
					sendmail(SYSADMIN,"Server is back up");
					sentmsg = false;
				}
			} else 
				print("Server is up");
            
	     	
	     
	  
	    } catch (TupleSpaceException tse) { 
	    	errmsg = "\n WhiteboardMonitor: \n Failure =" + tse.getMessage();
	    
	        if ( running)  {  // if it was running
	        	running = false;   
	    		print(errmsg,true);
	        	tse.printStackTrace();
	        	TupleSpace.cleanup(); 
	        	print("Server has gone down!");
	        	sendmail(SYSADMIN,errmsg);
	        	sentmsg = true;
	        } else {
	        	print(errmsg,true);

	        	print("Server is still down");
	        	//sendmail(SYSADMIN,errmsg);

	        }
	    	
	    } catch(Exception e) {
	    	System.out.println(e);
	        e.printStackTrace();
	        running = false; 
	        break;   // Unexecpected exception so terminate
	   	}
	   	
	   	if (! check)    // If we don't want to loop doing the check 
	   		break;
  	}
  	
  	print("Ended");
  }
  
  static void 
  print(String string) {
  	print(string,false);
  }
  
  static void
  print(String string,boolean printDate) {
  	DateFormat dateformat;
  
  	if (printDate) 
  		dateformat = DateFormat.getDateTimeInstance();
  	else 
  		dateformat = DateFormat.getTimeInstance(DateFormat.SHORT);

  	Date now = new Date();
  	
  	System.out.println(dateformat.format(now) +": " + string);
  }
  
  /**
  ** Use the TSpaces services running on the TSPACES server to sendmail
  ** to the sysadmin
  */
  static void 
  sendmail(String who, String msg) {
  	
  	
  	
  	try {
  		TupleSpace.cleanup();
        print("sendmail: "+who);
  		TupleSpace servers = new TupleSpace("Services",SERVICE_HOST);	    
	     
	    servers.write("SendInternal",who,msg);
	    TupleSpace.cleanup();
	} catch (TupleSpaceException tse) { 	  
	  
    	System.out.println(tse);
        tse.printStackTrace();
          
   	}

  }
}
/* $Log: WhiteboardMonitor.java,v $
/* Revision 2.1  1999/11/05 22:22:40  estesp
/* Update revision number to 2.1 on all files
/*
/* Revision 1.1.1.1  1999/11/05 16:24:53  estesp
/* Imported 2.1.0 release into Austin CVS
/*
 * Revision 1.2  1999/06/17 05:39:47  thodes
 *   Updated the inital checkin to append the "Log" field and
 * convert CR/LF to CR (for win/unix interop).
 *
 *   The inital checkin lower-cased directrory names, and omitted
 * many dirs/files that will added later, e.g., MoDAL stuff.
 *
 * All of the above will need to be done to all VSS-to-CVS
 * converted sources.  In summary, in moving from VSS to CVS, do this:
 *  - lower-case dir names
 *  - CR/LF --> CR
 *  - append CVS "Log" entties
 *
 * (a script that helps with #2 and #3 is in
 *     tspaces1:~thodes/bin/update-keywords.sh)
 * 
 */


